package us.versus.them.triangle_mountain;

class Triangle {

	var pt1:Pt3;
	var pt2:Pt3;
	var pt3:Pt3;
	var normal:Pt3;
	var color:Pt3;

	public function new( pt1, pt2, pt3 ) {
		this.pt1 = pt1;
		this.pt2 = pt2;
		this.pt3 = pt3;
	}

	public function split( max:Float, getMidPoint ) {//getMidPoint: Pt3 -> Pt3 -> Float -> Pt3 ) {
		var mid1 = getMidPoint( pt1, pt2, max );
		var mid2 = getMidPoint( pt2, pt3, max );
		var mid3 = getMidPoint( pt3, pt1, max );
		return [
			  new Triangle( pt1  , mid1 , mid3 )
			, new Triangle( mid1 ,  pt2 , mid2 )
			, new Triangle( mid3 , mid2 ,  pt3 )
			, new Triangle( mid1 , mid2 , mid3 )
		];
	}

	public function calculateNormal( pt_normals:Hash< Pt3 > ) {
		var e1 = new Pt3( 
			  pt1.x - pt2.x
			, pt1.y - pt2.y
			, pt1.z - pt2.z
		);
		var e2 = new Pt3( 
			  pt3.x - pt2.x
			, pt3.y - pt2.y
			, pt3.z - pt2.z
		);
		this.normal = new Pt3();
		this.normal.cross( e1, e2 );
		this.normal.normalize();

		this.getPtNormal( pt1, pt_normals ).add( normal );
		this.getPtNormal( pt2, pt_normals ).add( normal );
		this.getPtNormal( pt3, pt_normals ).add( normal );

		var y = ( this.pt1.y + this.pt2.y + this.pt3.y ) / 3;
		if ( y < 0.0125 ) { 
			 this.color = Color.YELLOW;
		} else {
			if ( y < 0.5 ) {
				this.color = Color.GREEN;
			} else {
				this.color = Color.WHITE;
			}
		}
	}

	public function getPtNormal( pt:Pt3, pt_normals:Hash< Pt3 > ) {
		var normal = pt_normals.get( pt.toString() );
		if ( null == normal ) {
			normal = new Pt3( 0, 0, 0 );
			pt_normals.set( pt.toString(), normal );
		}
		return normal;
	}

	public function draw( pt_normals:Hash< Pt3 > ) {
		color.color();

		if ( null == pt_normals ) {
			normal.normal();
		} else {
			getPtNormal( pt1, pt_normals ).normal();
		}
		pt1.vertex();
		
		if ( null == pt_normals ) {
			normal.normal();
		} else {
			getPtNormal( pt2, pt_normals ).normal();
		}
		pt2.vertex();

		if ( null == pt_normals ) {
			normal.normal();
		} else {
			getPtNormal( pt2, pt_normals ).normal();
		}
		//trace( normal.print() + " v. " + getPtNormal( pt1, pt_normals ).print() );
		pt3.vertex();
	}
}
